// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package com.geniusai.aip.auth.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geniusai.aip.auth.config.ExternalConfig;
import com.geniusai.aip.auth.domain.ResourceUsageTrendVO;
import com.geniusai.aip.auth.domain.UserDO;
import com.geniusai.aip.auth.domain.edsentity.ObjectUsage;
import com.geniusai.aip.auth.mapper.UserMapper;
import com.geniusai.aip.auth.service.NfsService;
import com.geniusai.aip.auth.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.geniusai.aip.auth.service.impl.UserServiceImpl.urlEncode;

/**
 * @author hml14563
 * @date 2021/9/29
 */
@Slf4j
@Service
public class NfsServiceImpl implements NfsService {

    @Autowired
    private UserMapper userdomapper;
    @Autowired
    private ExternalConfig externalConfig;

    private static final String GET_RESOURCE_USING_TREND_GRAPH = "/api/datasources/proxy/1/api/v1/query";
    private static final String AIP_NAMESPACE = "aip";

    @Override
    public ObjectUsage getObjectStorage() {
        ObjectUsage objectUsage = new ObjectUsage();

        // 查询已分配
        Long totalAllocatedVolumeSize = userdomapper.sumTotalAllocatedVolumeSize();
        totalAllocatedVolumeSize = totalAllocatedVolumeSize == null ? 0 : totalAllocatedVolumeSize;
        objectUsage.setTotalUsedBytes(totalAllocatedVolumeSize * 1024 * 1024 * 1024);

        // 查询总额
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("query", "max by (persistentvolumeclaim,namespace) (kubelet_volume_stats_capacity_bytes { namespace = \"" + AIP_NAMESPACE + "\" })");
        paramMap.put("time", (System.currentTimeMillis() / 1000) + "");
        URI uri = urlEncode(externalConfig.getGrafanaService(), Integer.parseInt(externalConfig.getGrafanaPort()), GET_RESOURCE_USING_TREND_GRAPH, paramMap);
        HttpGet httpGet = new HttpGet(uri);
        log.info("请求资源url：{}", uri.toString());

        try {
            String responseResult = HttpUtil.request(httpGet);
            ResourceUsageTrendVO resourceUsageTrendVO = parseVGpuResponseJson(responseResult);

            objectUsage.setTotalBytes(Long.parseLong(resourceUsageTrendVO.getResult().get(0).getY()));
        } catch (Exception e) {
            log.info("请求资源总额失败: " + e);
        }

        objectUsage.setTotalAvailBytes(objectUsage.getTotalBytes() - objectUsage.getTotalUsedBytes());
        return objectUsage;
    }


    public static ResourceUsageTrendVO parseVGpuResponseJson(String responseResult) {
        ResourceUsageTrendVO resourceUsageTrendVO = new ResourceUsageTrendVO();
        List<ResourceUsageTrendVO.Data> result = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(responseResult);
            if (!jsonNode.findPath("value").isEmpty()) {
                ResourceUsageTrendVO.Data data = new ResourceUsageTrendVO.Data();
                data.setX(jsonNode.findPath("value").get(0).toString().replace("\"", ""));
                data.setY(jsonNode.findPath("value").get(1).toString().replace("\"", ""));
                result.add(data);
            }
        } catch (JsonProcessingException e) {
            log.error("json数据解析异常：", e);
        }
        resourceUsageTrendVO.setResult(result);
        return resourceUsageTrendVO;
    }

    @Override
    public UserDO edsCreateEntrance(UserDO userDO) {
        return null;
    }

    @Override
    public void edsDeleteEntrance(List<String> deleteBucketsList, List<String> deleteUsersList) {

    }
}
